from rest_framework.views import APIView  # 导入APIView类用于创建RESTful API视图
from rest_framework.response import Response  # 导入Response类用于返回API响应
from rest_framework import status  # 导入status常量用于设置HTTP响应状态码
from .utils import generate_summary  # 导入你定义的生成摘要的工具函数
from rest_framework.permissions import IsAuthenticated
from .services.ai_manager import AIManager
from apps.note.models import Note
from django.core.cache import cache
from ..note.services.ai_service import ai_service, AIProcessingError
import logging
from datetime import datetime
from .services.ai_service import AIService
from typing import Dict

logger = logging.getLogger('apps')


class GenerateMemoSummary(APIView):
    """
    处理生成备忘录摘要的API视图
    """

    def post(self, request, *args, **kwargs):
        """
        处理POST请求，生成会议记录或任务清单的摘要

        参数:
        request: HTTP请求对象
        *args, **kwargs: 可选的额外参数

        返回:
        Response: 返回一个JSON响应，包含摘要或者错误信息
        """

        # 从请求体中获取 'content' 字段的数据，这里假设前端发送的JSON格式有一个 "content" 字段
        content = request.data.get("content")

        # 判断是否有传递 'content' 内容
        if content:
            # 调用 generate_summary 函数来生成摘要
            summary = generate_summary(content)

            # 如果成功生成摘要，返回摘要内容
            if summary:
                return Response({"summary": summary}, status=status.HTTP_200_OK)
            else:
                # 如果没有生成摘要，返回500内部服务器错误
                return Response({"error": "Failed to generate summary"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 如果没有传递 content，返回400错误，提示内容为空
        return Response({"error": "No content provided"}, status=status.HTTP_400_BAD_REQUEST)


class BaseResponse:
    @staticmethod
    def success(data=None, message="操作成功"):
        return Response({
            "status": "success",
            "message": message,
            "data": data
        })

    @staticmethod
    def error(message="操作失败", status=status.HTTP_400_BAD_REQUEST):
        return Response({
            "status": "error",
            "message": message
        }, status=status)


class AnalyzeNoteView(APIView):
    """分析笔记内容"""
    permission_classes = [IsAuthenticated]
    
    def post(self, request):
        try:
            # 获取请求参数
            note_id = request.data.get('note_id')
            content = request.data.get('content')
            analysis_type = request.data.get('analysis_type', 'comprehensive')  # 分析类型
            include_suggestions = request.data.get('include_suggestions', True)  # 是否包含建议
            
            # 参数验证
            if not note_id and not content:
                return BaseResponse.error("请提供笔记ID或文本内容")
                
            if content and len(content.strip()) < 10:
                return BaseResponse.error("文本内容太短，无法进行有效分析")

            # 获取内容
            try:
                if note_id:
                    note = Note.objects.get(id=note_id, user=request.user)
                    content = note.content
                    # 检查笔记是否为空
                    if not content or len(content.strip()) < 10:
                        return BaseResponse.error("笔记内容为空或太短，无法进行分析")
            except Note.DoesNotExist:
                return BaseResponse.error("笔记不存在", status.HTTP_404_NOT_FOUND)

            # 使用缓存避免重复分析
            cache_key = f"note_analysis_{hash(content)}_{analysis_type}"
            cached_result = cache.get(cache_key)
            
            if cached_result:
                logger.info("使用缓存的分析结果")
                analysis = cached_result
            else:
                # 调用 AI 服务分析内容
                analysis = ai_service.analyze_note(content)
                # 缓存结果（1小时）
                cache.set(cache_key, analysis, 3600)

            # 构建响应数据
            response_data = {
                "analysis": analysis,
                "metadata": {
                    "original_content": content[:200] + "..." if len(content) > 200 else content,
                    "content_length": len(content),
                    "analyzed_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "source_type": "note" if note_id else "direct_input",
                    "analysis_type": analysis_type,
                    "word_count": len(content.split()),
                    "is_cached_result": bool(cached_result)
                }
            }
            
            # 添加笔记相关信息
            if note_id:
                response_data["note_info"] = {
                    "note_id": note_id,
                    "note_title": note.title if hasattr(note, 'title') else None,
                    "created_at": note.created_at.strftime("%Y-%m-%d %H:%M:%S") if hasattr(note, 'created_at') else None,
                    "last_modified": note.updated_at.strftime("%Y-%m-%d %H:%M:%S") if hasattr(note, 'updated_at') else None
                }
            
            # 可选：保存分析历史
            try:
                self._save_analysis_history(request.user, content, analysis, note_id)
            except Exception as e:
                logger.warning(f"保存分析历史失败: {str(e)}")
            
            return BaseResponse.success(
                data=response_data,
                message="内容分析成功"
            )
            
        except AIProcessingError as e:
            logger.error(f"AI处理失败: {str(e)}")
            return BaseResponse.error(f"AI分析失败: {str(e)}")
        except Exception as e:
            logger.error(f"分析内容失败: {str(e)}")
            return BaseResponse.error(str(e))

    def _save_analysis_history(self, user, content, analysis, note_id=None):
        """保存分析历史"""
        from apps.ai.models import AIAnalysisHistory
        
        AIAnalysisHistory.objects.create(
            user=user,
            content_preview=content[:500],
            analysis_result=analysis,
            note_id=note_id,
            content_hash=hash(content)
        )


class GenerateSummaryView(APIView):
    """生成文本摘要的视图"""
    
    def post(self, request):
        try:
            # 获取请求参数
            text = request.data.get('text')
            summary_type = request.data.get('type', 'concise')
            language = request.data.get('language', 'zh')
            
            # 参数验证
            if not text:
                return Response({
                    'status': 'error',
                    'message': '请提供文本内容'
                }, status=400)
                
            if summary_type not in ['concise', 'detailed', 'structured']:
                return Response({
                    'status': 'error',
                    'message': '无效的摘要类型'
                }, status=400)
                
            if language not in ['zh', 'en']:
                return Response({
                    'status': 'error',
                    'message': '不支持的语言类型'
                }, status=400)
            
            # 调用AI服务生成摘要
            ai_service = AIService()
            result = ai_service.generate_summary(
                text=text,
                type=summary_type,
                language=language
            )
            
            return Response({
                'status': 'success',
                'message': '摘要生成成功',
                'data': result
            })
            
        except Exception as e:
            logger.error(f"生成摘要失败: {str(e)}")
            return Response({
                'status': 'error',
                'message': f"生成摘要失败: {str(e)}"
            }, status=400)


class GeneratePlanView(APIView):
    """生成计划"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            # 获取参数
            requirements = request.data.get('requirements')
            plan_type = request.data.get('plan_type', 'general')
            duration = request.data.get('duration', '1week')
            settings = request.data.get('settings', {})
            
            # 参数验证
            if not requirements:
                return BaseResponse.error("请提供计划需求")
            
            # 验证计划类型
            valid_plan_types = ['general', 'study', 'work', 'exam_prep', 'project']
            if plan_type not in valid_plan_types:
                return BaseResponse.error(f"不支持的计划类型，可选类型: {', '.join(valid_plan_types)}")
            
            # 使用缓存
            cache_key = f"plan_{hash(requirements)}_{plan_type}_{duration}"
            cached_result = cache.get(cache_key)
            
            if cached_result:
                logger.info("使用缓存的计划结果")
                plan = cached_result
            else:
                # 调用 AI 服务生成计划
                plan = ai_service.generate_plan(
                    text=requirements,
                    plan_type=plan_type,
                    duration=duration,
                    settings=settings
                )
                cache.set(cache_key, plan, 3600)
            
            # 构建响应
            response_data = {
                "plan": plan,
                "metadata": {
                    "plan_type": plan_type,
                    "duration": duration,
                    "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "settings_used": settings,
                    "is_cached": bool(cached_result)
                }
            }
            
            return BaseResponse.success(response_data, "计划生成成功")
            
        except Exception as e:
            logger.error(f"生成计划失败: {str(e)}")
            return BaseResponse.error(str(e))


class ProcessScheduleView(APIView):
    """处理日程"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        try:
            # 获取参数
            schedule_text = request.data.get('schedule_text') or request.data.get('content')
            settings = request.data.get('settings', {})
            include_reminders = settings.get('include_reminders', True)
            optimize_time = settings.get('optimize_time', True)
            reminder_advance = settings.get('reminder_advance', 30)
            
            # 参数验证
            if not schedule_text:
                return BaseResponse.error("请提供日程内容")
            
            # 调用 AI 服务处理日程
            schedule = ai_service.process_schedule(
                text=schedule_text,
                include_reminders=include_reminders,
                optimize_time=optimize_time,
                reminder_advance=reminder_advance
            )
            
            # 构建响应
            response_data = {
                "schedule": schedule,
                "metadata": {
                    "original_text": schedule_text,
                    "processed_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "settings_used": settings
                }
            }
            
            return BaseResponse.success(response_data, "日程处理成功")
            
        except Exception as e:
            logger.error(f"处理日程失败: {str(e)}")
            return BaseResponse.error(str(e))


class AIRecommendationView(APIView):
    """AI推荐视图"""
    
    def get(self, request):
        """获取个性化推荐"""
        try:
            user = request.user
            cache_key = f'ai_recommendations_{user.id}'
            
            # 尝试从缓存获取推荐
            recommendations = cache.get(cache_key)
            if not recommendations:
                ai_manager = AIManager()
                recommendations = ai_manager.generate_recommendations(user)
                
                # 缓存推荐结果，有效期1小时
                cache.set(cache_key, recommendations, 3600)
            
            return BaseResponse.success(recommendations)
            
        except Exception as e:
            return BaseResponse.error(str(e))


class AIReminderView(APIView):
    """AI提醒视图"""
    
    def get(self, request):
        """获取智能提醒"""
        try:
            user = request.user
            ai_manager = AIManager()
            reminders = ai_manager.get_smart_reminders(user)
            
            return BaseResponse.success(reminders)
            
        except Exception as e:
            return BaseResponse.error(str(e))


class AIAnalysisView(APIView):
    """AI分析视图"""
    permission_classes = [IsAuthenticated]
    
    async def post(self, request):
        try:
            content = request.data.get('content')
            analysis_type = request.data.get('type', 'general')
            context = request.data.get('context', {})
            
            if not content:
                return BaseResponse.error("请提供分析内容")
            
            # 使用缓存
            cache_key = f"ai_analysis_{hash(content)}_{analysis_type}"
            cached_result = cache.get(cache_key)
            
            if cached_result:
                return BaseResponse.success(cached_result)
            
            # 调用AI服务
            ai_service = AIService()
            result = await ai_service.analyze_content(content, analysis_type, context)
            
            # 缓存结果
            cache.set(cache_key, result, 3600)
            
            return BaseResponse.success(result)
            
        except Exception as e:
            logger.error(f"AI分析失败: {str(e)}")
            return BaseResponse.error(str(e))


class PersonalizedSuggestionsView(APIView):
    """个性化建议视图"""
    permission_classes = [IsAuthenticated]
    
    async def get(self, request):
        try:
            user_id = request.user.id
            context_data = await self._get_user_context(user_id)
            
            ai_service = AIService()
            suggestions = await ai_service.generate_personalized_suggestions(
                user_id=user_id,
                context_data=context_data
            )
            
            return BaseResponse.success(suggestions)
            
        except Exception as e:
            logger.error(f"生成个性化建议失败: {str(e)}")
            return BaseResponse.error(str(e))
    
    async def _get_user_context(self, user_id: int) -> Dict:
        """获取用户上下文数据"""
        # 实现获取用户数据的逻辑
        pass


class UserBehaviorAnalysisView(APIView):
    """用户行为分析视图"""
    permission_classes = [IsAuthenticated]
    
    async def get(self, request):
        try:
            user_id = request.user.id
            time_range = request.query_params.get('time_range', 'last_week')
            
            # 获取用户行为数据
            behavior_data = await self._get_behavior_data(user_id, time_range)
            
            ai_service = AIService()
            analysis = await ai_service.analyze_user_behavior(
                user_id=user_id,
                behavior_data=behavior_data
            )
            
            return BaseResponse.success(analysis)
            
        except Exception as e:
            logger.error(f"分析用户行为失败: {str(e)}")
            return BaseResponse.error(str(e))
